// const md5 = require("md5");
import { JWTHelper } from "../../utils/JWTHelper";
import { ForbiddenError } from "../../utils/errors";
import { pathToRegexp } from "path-to-regexp";

// 认证白名单
const whiteList = [
  {
    path: "/api/login",
    method: ["post"],
  },
  {
    path: "/api/logout",
    method: ["post"],
  },
  {
    path: "/api/captchaImage",
    method: ["get"],
  },
  {
    path: "/api/messageType/:x",
    method: ["get"],
  },
  {
    path: "/api/messageList/:x",
    method: ["get"],
  },
  {
    path: "/api/slideshow/:x",
    method: ["get"],
  },
  {
    path: "/api/cat/:x",
    method: ["get"],
  },
  {
    path: "/api/companyInfo/:x",
    method: ["get"],
  },
  {
    path: "/api/posterSet/list",
    method: ["get"],
  }, {
    path: "/api/utils/handler",
    method: ["get"],
  },
  {
    path: "/api/cattery/list",
    method: ["get"],
  },
];

function verificationToken(req: any, _res: any, next: any) {
  const result = whiteList.filter((item) => {
    const reg = pathToRegexp(item.path);

    return reg.test(req.path) && item.method.includes(req.method.toLocaleLowerCase());
  });

  // 进入此if证明不需要验证
  if (result.length) {
    next();
    return;
  }
  // 往下走证明需要验证
  // 但是没有 authorization 字段，证明未登录，直接抛出错误
  if (!req.headers["authorization"]) {
    throw new ForbiddenError("权限不足，请先登录");
  }

  let token = req.headers["authorization"].split(" ")[1]; // 获取请求头中的token

  const verResult = JWTHelper.verify(token);
  req.token = verResult;
  next();
}

export default verificationToken;
